﻿using Aliyun.OSS;

namespace Kz.Telegram.Bot.Infrastructure.Helpers
{
    public class OssHelper
    {
        public static string BaseOSSEndPoint = ConfigExtensionsHelper.app("OSSConstant", "BaseOSSEndPoint");
        public static string OSSAccessId = ConfigExtensionsHelper.app("OSSConstant", "OSSAccessId");
        public static string OSSAccessKey = ConfigExtensionsHelper.app("OSSConstant", "OSSAccessKey");
        public static string OSSBucket = ConfigExtensionsHelper.app("OSSConstant", "OSSBucket");
        public static string OSSEndPoint = ConfigExtensionsHelper.app("OSSConstant", "OSSEndPoint");

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">本地文件地址</param>
        /// <param name="type">mp3,mp4等</param>
        /// <returns></returns>
        public static string Upload(string path, string type,string ossDirectory)
        {
            try
            {
                using (var file = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    var ossClient = new OssClient(BaseOSSEndPoint, OSSAccessId, OSSAccessKey); //OssClient(OSSEndPoint, OSSAccessId, OSSAccessKey);
                    ObjectMetadata meta = new ObjectMetadata();
                    meta.ContentType = getContentType(type);
                    meta.ContentLength = file.Length;
                    string strExtensionName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.Name);
                    string key = ossDirectory.Trim('/') + "/" + strExtensionName;
                    PutObjectResult result = ossClient.PutObject(OSSBucket, key, file, meta);//上传图片
                    AccessControlList accs = ossClient.GetBucketAcl(OSSBucket);
                    var url = string.Format("{0}/{1}", OSSEndPoint, key);
                    return url;
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
                //return ex.Message;
            }
        }

        public static string getContentType(string type)
        {
            string ContentType = "";
            type = type.ToLower();
            switch (type)
            {
                case "mp3":
                    ContentType = "audio/mp3";
                    break;
                case "mp4":
                    ContentType = "video/mp4";
                    break;
                case "wav":
                    ContentType = "audio/wav";
                    break;
                case "txt":
                    ContentType = "text/plain";
                    break;
                default:
                    break;
            }
            return ContentType;
        }
    }
}
